/*
 * @Date: 2023-02-15 16:00:15
 * @LastEditTime: 2023-03-18 11:20:27
 * @FilePath: /hua-fei-chong-zhi/src/store/useSysStore.ts
 * 介绍:系统缓存仓库
 */
import { resetStore } from "@@/hooks/reset";
import toast from "@@/hooks/toast";
import { sdkConnect, sdkGetChainId, sdkIsEthereum } from "@@/sdk/web3Eth";
import * as tronWeb from "@@/sdk/tronWeb";
import { funDelay, getCurrentHrefQueryParam } from "@@/utils/tools/tools";
import { sdkWalletPlatformInfo } from "@@/sdk/tp";
import { apiLogin, Login } from "@@/api/module/sys";
import { i18n } from "@@/language";
import useUserinfoStore from "./useUserinfoStore";
import PubSub from "pubsub-js";
import router from "@@/router";

//@ts-ignore
const { t } = i18n.global;

export default defineStore("StoreSys", {
  //*全局仓库
  state: initState,
  //*全局函数
  actions: {
    /**是否币安链 */
    async isBab() {
      if (sdkIsEthereum()) {
        const { data } = await sdkGetChainId();
        if (Number(data) == 56) return true;
      }
      return false;
    },
    async login(query: AnyObj, count: number = 1): Promise<boolean> {
      console.log("query参数", query);
      router.replace({ name: "home" });
      /**重试登录次数 */
      const max = 5;
      const loginDelay = () => {
        resetStore();
        if (count > max) return false;
        return funDelay(this.login, [query, count]);
      };
      console.log(`第${count}次尝试登录`);
      toast.loading(`${t("zhen-zai-lian-jie")}...${count}/${max}`);
      count++;
      if (await this.isBab()) {
        const res = await this.connectEth(query.invit);
        if (res === true) return res;
        return loginDelay();
      }
      const res = await this.connectTron(query.invit);
      if (res === true) return res;
      return loginDelay();
    },
    /**连接波场钱包 */
    async connectTron(invit?: string): Promise<boolean> {
      console.log("连接波场钱包");
      const connectRes = await tronWeb.sdkConnect();
      const { data } = await sdkWalletPlatformInfo();
      if (!connectRes.status) {
        toast.error(connectRes.message);
        return false;
      }
      /**钱包名称 */
      const walletName = data?.name;
      const loginRes = await this.requestLogin({
        chainId: 0,
        nwtworkId: 0,
        accounts: connectRes.data!,
        invit,
        clientId: "123456789",
        code: "123456789",
        that_wallet_name: walletName || "",
      });
      if (!loginRes) {
        return false;
      }
      return true;
    },
    /**以太坊钱包连接 */
    async connectEth(invit?: string): Promise<boolean> {
      console.log("连接eth钱包");
      const connectRes = await sdkConnect();
      if (!connectRes.status) {
        toast.error(connectRes.message + ": ethereum");
        return false;
      }
      const [getChainIdRes, { data }] = await Promise.all([
        sdkGetChainId(),
        sdkWalletPlatformInfo(),
      ]);
      if (!getChainIdRes.status) {
        toast.error(`${t("lian-jie-qian-bao-shi-bai")} : thereum`);
        return false;
      }
      /**钱包名称 */
      const walletName = data?.name;
      const loginRes = await this.requestLogin({
        chainId: getChainIdRes.data!,
        nwtworkId: 0,
        accounts: connectRes.data!,
        invit,
        clientId: "123456789",
        code: "123456789",
        that_wallet_name: walletName || "",
      });
      if (!loginRes) return false;
      return true;
    },
    /**请求登录并储存信息 */
    async requestLogin(params: Login.Req): Promise<boolean> {
      const { lastLoginInfo } = this;
      //* 如果所有账户信息都相同而且没有邀请码则不请求服务器
      if (
        params.accounts == lastLoginInfo?.accounts &&
        params.chainId == lastLoginInfo?.chainId &&
        !params.invit
      ) {
        return await this.logined();
      }
      resetStore();
      const res = await apiLogin(params);
      if (!res) return false;
      this.$patch((state) => {
        state.isLogin = true;
        state.reqHeader = {
          ...state.reqHeader,
          authorization: `Bearer ${res.access_token}`,
        };
        state.tokenInfo = res;
        state.lastLoginInfo = params;
      });
      return await this.logined();
    },
    async logined() {
      const userinfoStore = useUserinfoStore();
      const { is } = storeToRefs(userinfoStore);
      toast.loading(t("zhen-zai-chu-shi-hua-shu-ju"));
      await Promise.all([
        userinfoStore.getBaseData(),
        userinfoStore.getUserinfo(),
      ]);
      toast.close();
      if (is.value?.isVip === true) router.replace({ name: "vipHome" });
      else router.replace({ name: "home" });
      setTimeout(() => toast.success(t("deng-lu-cheng-gong")), 1000);
      setTimeout(() => PubSub.publish("logined"), 2000);
      return true;
    },
  },
  //*计算属性
  getters: {},
  //*仓库数据缓存
  persist: [
    {
      key: "StateSys",
      storage: localStorage, //指定储存位置
    },
  ],
});
/**state类型定义 */
interface StoreSys {
  isLogin: boolean;
  tokenInfo: Login.Res | undefined;
  setting: Setting;
  walletinfo: Walletinfo | undefined;
  reqHeader: AnyObj | undefined;
  lastLoginInfo: LastLoginInfo | undefined;
}
interface LastLoginInfo extends Login.Req {}
/**设置 */
export interface Setting {
  language: string;
}
interface Walletinfo {
  name?: string;
  account: string;
}
/**初始化pinia */
function initState(): StoreSys {
  return {
    isLogin: false,
    setting: {
      language: "zh-CN",
    },
    reqHeader: undefined,
    walletinfo: undefined,
    tokenInfo: undefined,
    lastLoginInfo: undefined,
  };
}
